<template>
  <div class="app-container">
    <!-- <t-Search /> -->
    <el-form :model="param" ref="publishRef" :rules="publishRules" label-width="0">
      <el-card class="form_card">
        <span style="font-weight: 700;font-size: 15px;">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>基本信息
        </span>
        <div style="margin:40px 40px 0 40px">
          <el-row style="width:600px;min-width: 400px;">
            <el-col :span="11">
              <el-form-item prop="boxStartCity">
                <div>
                  <redStar />出发城市(多选)
                </div>
                <city-select ref="startCityRef" v-model="param.boxStartCity" :needInfo="true" :multiple="true"
                  :multipleLimit="10" :cityList="startCityList" @cityId="startCityInfo"
                  style="width: 100%;"></city-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: center;margin-top: 40px; ">
              <svg-icon icon-class="toRight" />
            </el-col>
            <el-col :span="11">
              <el-form-item prop="boxBackCity">
                <div>
                  <redStar />到达城市(多选)
                </div>
                <city-select ref="backCityRef" v-model="param.boxBackCity" :needInfo="true" :multiple="true"
                  :multipleLimit="10" :cityList="backCityList" @cityId="backCityInfo" @clear="cityClear('end')"
                  style="width: 100%;"></city-select>
              </el-form-item>
            </el-col>
          </el-row>
          <span style="color: red;">* </span>
          <span style="font-size: 12px">多选城市不超过10个</span>
        </div>
      </el-card>

      <el-card class="form_card" style="margin-top: 15px;">
        <span style="font-weight: 700;font-size: 15px;">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>回调信息
        </span>
        <div style="margin:40px 40px 0 40px">
          <el-row style="width:100%;min-width: 400px;">
            <el-col :span="12">
              <el-form-item>
                <div>箱型</div>
                <div style="width:100%; ">
                  <el-radio-group v-model="param.boxSize" @change="boxSizeChange" :disabled="validateStartCity"
                    style="float: left;">
                    <el-radio-button v-for="item in param.sizeList" :key="item.value" :value="item.value"
                      :label="item.label" />
                  </el-radio-group>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <div>箱况</div>
                <div style="width:100%">
                  <el-checkbox-group v-model="param.boxCase" @change="boxCaseChange" :disabled="validateStartCity"
                    style="float: left;">
                    <el-checkbox-button v-for="item in param.caseList" :key="item.value" :value="item.value"
                      :label="item.label"></el-checkbox-button>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <div style="width:100%">
              <redStar />回调箱规格
            </div>
            <el-table :data="tableData" style="width: 100%">
              <el-table-column prop="size" label="箱型" width="180"></el-table-column>
              <el-table-column prop="info" label="箱况" width="180"></el-table-column>
              <el-table-column prop="totalWeight" label="总重(kg)" width="180"></el-table-column>
              <el-table-column label="数量" width="180">
                <template #default="scope">
                  <el-input-number v-model="scope.row.number" :controls="false" :min="1" :max="999"
                    @blur="scope.row.number = scope.row.number ? scope.row.number : 1" />
                </template>
              </el-table-column>
              <el-table-column prop="startCity" label="出发城市">
                <template #header>
                  <el-select v-model="param.tableSelectCity" @change="tableSelectCityChange" placeholder="出发城市"
                    style="width: 200px">
                    <el-option v-for="item in tableSelectCity" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column>
                <template #header>
                  <el-button type="text" @click="handleDelete" :icon="Delete"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="dynamicTags.length > 10" style="margin-top: 10px;">
              <el-button type="primary" @click="handleShowMore">
                <span v-if="limit10">显示更多</span>
                <span v-else>收起</span>
              </el-button>
            </div>
          </el-form-item>

          <el-form-item style="max-width:500px">
            <div>货品名称</div>
            <el-input v-model="param.cargoName" maxlength="50" type="textarea" rows="2" show-word-limit
              style="width: 100%;"></el-input>
          </el-form-item>

          <el-form-item style="width:240px">
            <div>修箱费</div>
            <div style="width: 100%;"><b>还箱时，实报实销</b></div>
          </el-form-item>

          <el-form-item prop="overdueFeeDay">
            <div style="width: 100%;">
              <redStar />超期费
            </div>
            <span>超期1天后 $
              <el-input-number v-model.trim="param.overdueFeeDay"
                @blur="param.overdueFeeDay = param.overdueFeeDay ? param.overdueFeeDay : 1" :controls="false" :min="0"
                :max="999" :precision="0" placeholder="< 1000" style="width: 80px" />
            </span>&nbsp; 箱/天
          </el-form-item>
          <el-row>
            <el-form-item prop="lossDay" style="float: left;">
              超期 &nbsp;
              <el-input-number v-model.trim="param.lossDay" @blur="param.lossDay = param.lossDay ? param.lossDay : 1"
                :controls="false" :min="0" :max="999" :precision="0" placeholder="< 1000" style="width: 80px" />
              &nbsp;天后，仍未还箱，视为灭失，灭失费为
            </el-form-item>
            <el-form-item prop="lossFee">
              &nbsp;$&nbsp;
              <el-input-number v-model.trim="param.lossFee" @blur="param.lossFee = param.lossFee ? param.lossFee : 1"
                :controls="false" :min="1" :max="9999" :precision="0" placeholder="< 10000" style="width: 80px" />
            </el-form-item>
          </el-row>

          <el-form-item prop="boxUsagePeriod" style="width:240px">
            <div>
              <redStar />箱使期&nbsp;&nbsp;
            </div>
            <el-input-number v-model="param.boxUsagePeriod"
              @blur="param.boxUsagePeriod = param.boxUsagePeriod ? param.boxUsagePeriod : 1" :controls="false" :min="0"
              :max="999" :precision="0" placeholder="< 1000" style="width: 80px" />
            &nbsp;&nbsp;天
          </el-form-item>

          <el-form-item style="width:240px">
            <div>总回调箱量</div>
            <el-input v-model="totalInventory" disabled style="width: 100%">
              <template #append>个</template>
            </el-input>
          </el-form-item>

          <el-form-item style="width:240px">
            <div>
              <redStar />上架方式
            </div>
            <el-select v-model="param.mode" style="width:100%" placeholder="选择还箱城市">
              <el-option v-for="item in param.modeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <div>备注</div>
            <el-input v-model="param.remark" type="textarea" rows="5" show-word-limit maxlength="200"
              style="width: 100%;" />
          </el-form-item>

        </div>
      </el-card>

      <el-card class="form_card" style="margin-top: 15px;">
        <span style="font-weight: 700;font-size: 15px;">
          <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span> 图文描述
        </span>
        <div style="margin:40px 40px 0 40px">
          <el-form-item>
            <div>
              <redStar />主图 <span style="color: #999;">(最多上传6张)</span>
            </div>
            <div style="width:100%">
              <div class="div-box-dark">
                <upload-Img ref="uploadImgRef" :urlList="param.showMainImgList" @uploadSccess="uploadMainSccess"
                  @uploadRemoveSccess="uploadRemoveMainImgSccess" style="width:1000px;height: 1000px;" />
                <p>请上传 png/jpg 主图，大小不能超过3M，建议图片像素高于700*700px</p>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div>详情描述</div>
            <div style="width:100%">
              <div style="min-height:100px;width: 600px;">

                <div v-for="(mark, index) in param.marks">
                  <el-button v-if="index > 0" :icon="CloseBold" type="info" circle @click="handleClose(index)"
                    style="float: right;width:10px;height:10px"></el-button>
                  <div class="div-box-dark">
                    <el-input v-model="mark.textVal" placeholder="在这里介绍您的集装箱" type="textarea" rows="5" show-word-limit
                      maxlength="200" style="width: 100%;" />
                    <!-- <upload-Img :ref="(el) => handleSetInputMap(el, index)" :urlList="mark.imgInfo"
                      style="width:1000px;height: 1000px; " /> -->
                    <upload-Img :ref="(el) => handleSetInputMap(el, index)" :urlList="mark.imgInfo"
                      @uploadSccess="uploadDetailSccess($event, index)"
                      @uploadRemoveSccess="uploadRemoveDetailImgSccess($event, index)"
                      style="width:1000px;height: 1000px; " />
                  </div>
                </div>
                <el-button :icon="Plus" type="info" size="small" @click="handleAdd">新增描述</el-button>

              </div>
            </div>
          </el-form-item>
        </div>
      </el-card>

      <el-form-item>
        <div style="height: 100px;width: 100%;"></div>
        <div v-if="param.isLoading" style="margin:auto;color: chocolate;">数据提交中......</div>
        <div v-else style="margin:auto;">
          <el-button @click="onSave('save')">保存待发布</el-button>
          <el-button type="primary" @click="onSave('publish')">立即上架</el-button>
        </div>
      </el-form-item>

    </el-form>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" :title="param.operate == 'add' ? '新增' : '删除'" width="500">
      <!-- <span>This is a message</span> -->
      <el-input v-if="param.operate == 'add'" v-model="param.addElement"></el-input>
      <span v-else> 确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="param.dialogVisible = false">
            取消
          </el-button>
          <el-button @click="handleOk">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import redStar from '@/views/components/redStar.vue';
import { Plus, Delete, CloseBold } from '@element-plus/icons-vue'
import { computed, getCurrentInstance, onActivated, onMounted, reactive, ref, watch } from 'vue';
import uploadImg from '@/components/upload/img.vue'
import citySelect from '@/components/citySelect'
import { getCityInventory, agentSubmit, agentTobeReleased, getBoxInfo } from '@/api/boxCallBack'
import { useRoute, useRouter } from 'vue-router';
import orderInfo from '@/store/modules/order'
import { ElMessage, ElMessageBox } from 'element-plus';
const router = useRouter();
let param = reactive({
  historyList: [],
  historyIds: [],
  boxSize: '40HQ',
  boxCase: ['fit'],
  loading: false,
  boxSizeHistory: {}, // eg:{40HQ:[{ size: string; info: any; price: string; num: string; }],20HQ:[],40GP:[],200GP:[]} 
  totalWeight: 1,
  weightOptions: [
    { value: 1, label: '30480' },
    { value: 2, label: '32500' },
  ],
  mode: 5,
  modeList: [
    { value: 5, label: '立即上架' },
    { value: 10, label: '放入仓库' },
  ],
  marks: [{ textVal: '' }],
  period: '',
  filter: { 5: 'allNew', 10: 'nextNew', 15: 'fit', 20: 'mix' },
  filterSize: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' },
  filterInfo: { 15: '适货', 10: '次新', 5: '全新', 20: '混提' },
  caseList: [
    { value: 'fit', label: '适货' },
    { value: 'nextNew', label: '次新' },
    { value: 'allNew', label: '全新' },
    { value: 'mix', label: '混提' },
  ],
  sizeList: [
    { value: '40HQ', label: '40HQ' },
    { value: '40GP', label: '40GP' },
    { value: '20HQ', label: '20HQ' },
    { value: '20GP', label: '20GP' },
  ],
  boxStartCity: [],
  boxBackCity: [],
  boxStartCityData: [],
  boxBackCityData: [],
  startCityOptions: [],
  backCityOptions: [],
  dialogVisible: false,
  operate: '',
  addElement: '',
  addType: 'case', // case,size
  overdueFeeDay: 0,
  boxCaseFilter: { 'fit': '适货', 'nextNew': '次新', 'allNew': '全新', 'mix': '混提' },
  boxSizeFilter: { '40HQ': 5, '40GP': 10, '20HQ': 15, '20GP': 20 }
})
//总库存
const totalInventory = computed(() => {
  let num = 0
  console.log(dynamicTags.value)
  if (dynamicTags.value && dynamicTags.value.length > 0) {
    num = dynamicTags.value.reduce((pre, cur) => {
      return pre + cur.number
    }, 0)
  }
  return num
})
//回调箱规格table
let dynamicTags = ref([])
const limit10 = ref(true)
const tableData = computed(() => {
  let data: Array<any> = []
  if (param.tableSelectCity) {
    data = sortCity(dynamicTags.value.filter(item => param.tableSelectCity == item.startCityId))
  } else {
    data = sortCity(dynamicTags.value)
  }
  if (limit10.value) {
    data = data.slice(0, 10)
  }
  return data
})

onActivated(() => {
  const rowData = orderInfo().rowData
  if (!rowData) return
  showData(rowData)
})

//初始化显示数据
const startCityList = ref([])
const backCityList = ref([])
const optId = ref(null)
const isInfo=ref(false)
const showData = async (value: any) => {
  if (!value) return
  const row = value
  let id = row.id // row.id 
  let isAdd = row.id ? false : true
   if(row?.isInfo){
    isInfo.value=row.isInfo
  }
  optId.value = id
  if (id) {
    console.log('edit')
    await getBoxInfo(id).then(async (res: any) => {
      const val = res.data
      const filter: any = { 5: 'allNew', 10: 'nextNew', 15: 'fit', 20: 'mix' }
      const filterSize: any = { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }
      const filterInfo: any = { 15: '适货', 10: '次新', 5: '全新', 20: '混提' }

      //城市展示  
      const carryCity = JSON.parse(val.carryCity)
      const returnCity = JSON.parse(val.returnCity)
      startCityList.value = carryCity.map(item => {
        return { value: item.cityId, label: item.cityName, countryId: item.countryId, countryCName: item.countryName }
      })
      backCityList.value = returnCity.map(item => {
        return { value: item.cityId, label: item.cityName, countryId: item.countryId, countryCName: item.countryName }
      })
      param.boxStartCity = carryCity.map(item => item.cityId)
      param.boxBackCity = returnCity.map(item => item.cityId)

      //获取可用库存
      let ids = carryCity.map(item => item.cityId)
      await getNumArry(ids)
      param.historyIds = JSON.parse(JSON.stringify(ids)) //出发城市 历史数据赋值

      //箱型箱况
      const boxType = val.releaseCallbackPriceList[0] ? val.releaseCallbackPriceList[0].boxType : 5
      const boxCase = val.releaseCallbackPriceList.filter(item => item.boxType == boxType).map(item => filter[item.boxCondition])
      param.boxSize = filterSize[boxType] //箱型
      param.boxCase = [...new Set(boxCase)] //箱况
      param.historyList = JSON.parse(JSON.stringify(param.boxCase)) //箱况 历史数据赋值

      //列表
      let tagArry: any = []
      val.releaseCallbackPriceList.map(item => {
        const num = getNum(item.boxType, item.boxCondition, item.carryCityId) // 获取可用库存 
        tagArry.push({
          size: filterSize[item.boxType], info: filterInfo[item.boxCondition], number: item.inventory,
          num: num, case: filter[item.boxCondition], totalWeight: item.totalWeight, startCity: item.carryCityName, startCityId: item.carryCityId, countryCName: item.carryCountryName, countryId: item.carryCountryId
        })
      })
      console.log(tagArry)
      dynamicTags.value = tagArry

      //其他
      param.cargoName = val.cargoName
      param.overdueFeeDay = val.overdueFeeDay
      param.lossDay = val.lossDay
      param.lossFee = val.lossFee
      param.boxUsagePeriod = val.boxUsagePeriod
      param.mode = val.groundingMethod
      param.marks = JSON.parse(val.detailFileList) || []
      param.remark = val.remark
      param.showMainImgList = JSON.parse(val.mainFileList)
      param.mainImgList = JSON.parse(val.mainFileList) // 校验

      //编辑保存用 的入参
      param.boxStartCityData = []
      carryCity.forEach(item => {
        param.boxStartCityData.push({
          id: item.cityId,
          cityCName: item.cityName,
          countryId: item.countryId,
          countryCName: item.countryName
        })
      })
      param.boxBackCityData = []
      returnCity.forEach(item => {
        param.boxBackCityData.push({
          id: item.cityId,
          cityCName: item.cityName,
          countryId: item.countryId,
          countryCName: item.countryName
        })
      })
    })
  }

  if (isAdd) {
    clearData()
  }
}
//清空数据
const clearData = () => {
  optId.value = null
  // param.boxStartCity = []
  param.boxBackCity = []
  // startCityList.value = []
  backCityList.value = []

  param.marks = [{ textVal: '', imgInfo: [] }]
  param.loading = false
  param.boxSizeHistory = {}// eg={40HQ:[{ size: string; info: any; price: string; num: string; }],20HQ:[],40GP:[],200GP:[]} 
  param.totalWeight = 1
  param.period = ''
  param.overdueFeeDay = 10
  param.lossDay = 10
  param.lossFee = 10
  param.boxUsagePeriod = 60
  param.period = 15
  param.showMainImgList = []
  setBoxTypeBoxCondition()
  param.historyList = []
}

//清空箱型箱况
const setBoxTypeBoxCondition = () => {
  param.boxSize = '40HQ'
  param.boxCase = []
  dynamicTags.value = []  //[{ size: param.boxSize, info: '适货', case: 'fit', price: '1', num: '0' }]
  param.boxStartCity = []
  startCityList.value = []
}

//删除
const handleDelete = (index: any) => {
  setBoxTypeBoxCondition()
}

//
const handleShowMore = () => {
  limit10.value = !limit10.value
}

// 取消城市
const cityClear = (val: string) => {
  if (val == 'end') {
    param.boxBackCity = []
    backCityList.value = []
  }
}

// 获取城市库存list
const getNumArry = (ids: any) => {
  getCityInventory(ids).then((res: any) => {
    param.numArry = res.data
  })
}

// 城市排序
const sortCity = (cityArry: any) => {
  // 使用 reduce 方法将相同 id 的城市分组
  const grouped = cityArry.reduce((acc, city) => {
    if (!acc[city.startCityId]) {
      acc[city.startCityId] = [];
    }
    acc[city.startCityId].push(city);
    return acc;
  }, {});
  // 将分组的城市展平为一个数组
  const sortedArray = Object.values(grouped).flat();
  return sortedArray;
}

// 出发城市
const startCityRef = ref()
const startCityInfo = (ids: any, data: any) => {
  const historySet = new Set(param.historyIds)
  const newSet = new Set(ids)
  const addItem = ids.find(item => !historySet.has(item)) // 新增项
  const removeItem = param.historyIds.find(item => !newSet.has(item)) //删除项
  console.log('新增' + addItem)
  console.log('删除' + removeItem)
  if (removeItem) {
    param.tableSelectCity = null
    dynamicTags.value = dynamicTags.value.filter(item => ids.includes(item.startCityId)) //出发城市变更时同步回调箱规格  
    if (dynamicTags.value.length == 0) param.historyList = []
  }
  if (addItem) {
    param.tableSelectCity = null
    let totalWeight = param.boxSizeFilter[param.boxSize] > 10 ? '30480' : '30480/32500'
    param.boxCase.forEach(item => {
      const city = data.find(item => item.id == addItem)
      dynamicTags.value.push({ size: param.boxSize, info: param.boxCaseFilter[item], case: item, totalWeight: totalWeight, number: 0, startCity: city.cityCName, startCityId: city.id })
    })
  }
  param.boxStartCity = ids
  param.boxStartCityData = data
  param.historyIds = JSON.parse(JSON.stringify(ids)) //历史数据
  getNumArry(ids)
}

// 到达城市
const backCityInfo = (ids: any, data: any) => {
  param.boxBackCity = ids
  param.boxBackCityData = data
}

// 城市下拉框数据
const tableSelectCity = computed(() => {
  return param.boxStartCityData.map(item => { return { value: item.id, label: item.cityCName, countryId: item.countryId, countryCName: item.countryCName } })
})

// 触发城市下拉框数据
const tableSelectCityChange = (val: any) => {
}
//获取某箱型下的箱况
const getBoxCaseBySize = (size: any) => {
  const boxType = ['40HQ', '40GP', '20HQ', '20GP']
  let boxCase: Object = {} //eg={40HQ:[{ size: string; info: any; price: string; num: string; }],20HQ:[],40GP:[],200GP:[]} 
  boxType.forEach(type => {
    boxCase[type] = dynamicTags.value.filter(item => item.size == size).map(item => item.case)
  })
  return boxCase[size]
}

// 箱型 
const boxSizeChange = (size: any) => {
  param.boxCase = getBoxCaseBySize(size)
  param.historyList = param.boxCase
  // console.log(param.boxCase)
}

// 箱况
const boxCaseChange = (list: any) => {
  const historySet = new Set(param.historyList)
  const newSet = new Set(list)
  const addItem = list.find(item => !historySet.has(item)) // 新增项
  const removeItem = param.historyList.find(item => !newSet.has(item)) //删除项
  console.log(param.historyList)
  console.log('新增' + addItem)
  console.log('删除' + removeItem)
  if (addItem) {
    param.boxStartCityData.forEach(city => {
      let totalWeight = param.boxSizeFilter[param.boxSize] > 10 ? '30480' : '30480/32500'
      dynamicTags.value.push({ size: param.boxSize, info: param.boxCaseFilter[addItem], case: addItem, totalWeight: totalWeight, number: 1, startCity: city.cityCName, startCityId: city.id })
    })
  }
  if (removeItem) {
    dynamicTags.value = dynamicTags.value.filter(item => {
      console.log(param.boxStartCity)
      console.log(item)
      return !(item.size == param.boxSize && item.info == param.boxCaseFilter[removeItem] && param.boxStartCity.includes(item.startCityId))
    })
  }
  console.log(dynamicTags.value)
  //历史数据
  param.historyList = JSON.parse(JSON.stringify(list))
  param.boxSizeHistory[param.boxSize] = JSON.parse(JSON.stringify(dynamicTags.value))
}

// 库存
// const getNum = (boxSize, el, cityId) => {
//   let num = 0
//   const filter = { 'fit': 15, 'nextNew': 10, 'allNew': 5, 'mix': 20 }
//   const filterSize = { '40HQ': 5, '40GP': 10, '20HQ': 15, '20GP': 20 }
//   const boxCondition = filter[el]
//   const type = filterSize[boxSize]
//   if (param.numArry && param.numArry.length > 0) {
//     const obj = param.numArry.find((item: any) => item.boxType == type && item.boxCondition == boxCondition && item.cityId == cityId) || { inventory: 0 }
//     num = obj.inventory
//   }
//   return num
// }
// 库存
const getNum = (boxType, boxCondition, cityId) => {
  let num = 0
  if (!param.numArry || param.numArry.length < 1) return
  if (boxCondition == 20) { // 20-混提
    param.numArry.filter((item: any) => {
      if (item.cityId == cityId && item.boxType == boxType && item.boxCondition != 5) {
        if (item.inventory < 0) return
        num += item.inventory || 0
      }
    })
  } else {
    const obj = param.numArry.find((item: any) => item.boxType == boxType && item.boxCondition == boxCondition && item.cityId == cityId) || { inventory: 0 }
    num = obj.inventory
  }
  return num
}

// marks
const handleClose = (val: any) => {
  param.marks.splice(val, 1)
}
const handleAdd = (val: any) => {
  param.marks.push({ textVal: '' })
}

const handleOk = () => {
  param.dialogVisible = false
  if (param.operate == 'add') {
    // console.log(param.addType)
    if (param.addType == 'case') {
      let index = param.caseList.length
      param.caseList.push({ value: 'addElement' + index, label: param.addElement })
    }
    if (param.addType == 'size') {
      param.sizeList.push({ value: param.addElement, label: param.addElement })
    }
    param.addElement = ''
  }
  if (param.operate == 'delete') {
    if (param.addType == 'size') {// param.boxSize
      const index = param.sizeList.findIndex((item: any) => {
        return item.value == param.boxSize
      })
      if (index != -1) {
        param.sizeList.splice(index, 1)
      }
    }
    if (param.addType == 'case') {//param.boxCase
      param.boxCase.map((val: any) => {
        let index = param.caseList.findIndex((item: any) => {
          return item.value == val
        })
        if (index != -1) {
          // indexList.push(index)
          param.caseList.splice(index, 1)
        }
      })
    }

  }

}

//上传成功的 
const uploadMainSccess = (data: any) => {
  param.showMainImgList.push(data)
}
const uploadDetailSccess = (data: any, index: number) => {
  let mark = param.marks[index]
  mark.imgInfo.push(data)
}
//img删除成功
const uploadRemoveMainImgSccess = (data: any) => {
  let index = param.showMainImgList.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index != -1) {
    param.showMainImgList.splice(index, 1)
  }
}
const uploadRemoveDetailImgSccess = (data: any, index: number) => {
  let mark = param.marks[index]
  let index1 = mark.imgInfo.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index1 != -1) {
    mark.imgInfo.splice(index1, 1)
  }
  if (mark.imgInfo.length == 0 && !mark.textVal) {
    param.marks.splice(index, 1)
  }
}

// 提交 
const uploadImgRef = ref()
const uploadRef = {}
const handleSetInputMap = (el, index: number) => {
  if (el) {
    uploadRef[`imgRef${index}`] = el;
  }
};
const { proxy } = getCurrentInstance();
const onSave = async (opr: any) => {
  let template = {
    "carryCity": cityStr(param.boxStartCityData),
    "returnCity": cityStr(param.boxBackCityData),
    "cargoName": param.cargoName,
    "repairFee": -1, // 修箱费 -1 表示实报实销
    "repairFeeCurrency": "USD",
    "boxUsagePeriod": param.boxUsagePeriod,
    "overdueFeeDay": param.overdueFeeDay,
    "overdueFeeCurrency": "USD",
    "lossDay": param.lossDay,
    "lossFee": param.lossFee,
    "groundingMethod": param.mode,
    "remark": param.remark,
    "releaseCallbackPriceList": releaseCallbackPriceListFormatData(dynamicTags.value),
    "mainFileList": JSON.stringify(param.showMainImgList), //主图,
    "detailFileList": JSON.stringify(param.marks), //详情信息 textVal
    "id": null
  }
  if (optId.value) {
    template.id = optId.value
  }
  if (opr == 'save') {
    param.isLoading = true
    await agentTobeReleased(template).then((res: any) => {
      param.isLoading = false
      router.back()
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })
  }
  if (opr == 'publish') {
    param.isLoading = true
    proxy.$refs.publishRef.validate(valid => {
      if (!valid) {
        param.isLoading = false
        return
      }
      if (param.showMainImgList.length === 0) {
        param.isLoading = false
        return ElMessage.warning('请上传主图！')
      }
      // if (param.marks.length == 0 || !param.marks[0].imgInfo || param.marks[0].imgInfo.length === 0) {
      //   param.isLoading = false
      //   return ElMessage.warning('请上传详情图！')
      // }
      agentSubmit(template).then((res: any) => {
        param.isLoading = false
        router.back()
      }).catch((err: any) => {
        setTimeout(() => {
          param.isLoading = false
        }, 2000)
      })
    })
  }
}

//功能函数
const cityStr = (arry: any) => {
  let citys: any = []
  arry.forEach((item: any) => {
    let city = { "cityId": item.id, "cityName": item.cityCName, "countryId": item.countryId, "countryName": item.countryCName }
    citys.push(city)
  })
  return JSON.stringify(citys)
}

/*
*param array [{"size":"40HQ","info":"适货","case":"fit","price":"1","num":0,"number":0,"totalWeight":'30480/32500',startCity: '郑州', startCityId: 1, countryCName:'中国', countryId: '1'}]
*return [{ "boxType": 5, "boxCondition": 5, "totalWeight": 32580, "inventory": 1, "carryCityId": 1, "carryCityName": "郑州", "carryCountryId": 1, "carryCountryName": "中国" }]
*/
const releaseCallbackPriceListFormatData = (arry: any) => {
  const result: any = []
  const filter: any = { 'fit': 15, 'nextNew': 10, 'allNew': 5, 'mix': 20 }
  const filterSize: any = { '40HQ': 5, '40GP': 10, '20HQ': 15, '20GP': 20 }
  arry.map((el: any) => {
    if (el.number - 0 > 0) {
      result.push({
        "boxType": filterSize[el.size],
        "boxCondition": filter[el.case],
        "totalWeight": el.totalWeight,
        "inventory": el.number - 0,
        "carryCityId": el.startCityId,
        "carryCityName": el.startCity,
        "carryCountryId": el.countryId,
        "carryCountryName": el.countryCName,
      })
    }
  })
  return result
}

//校验
const validateMainImgList = (rule: any, value: any, callback: any) => {
  if (value) {
    const length = value.length
    if (length < 1) {
      callback(new Error('不能为空'))
    } else {
      callback()
    }
  } else {
    callback(new Error('不能为空'))
  }
}
const publishRules = {
  boxBackCity: [{ required: true, trigger: "change", message: "不能为空" }],
  boxStartCity: [{ required: true, trigger: "change", message: "不能为空" }],
  period: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  overdueFeeDay: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  lossFee: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  lossDay: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  boxUsagePeriod: [
    { required: true, trigger: "blur", message: "不能为空" },
  ],
  mainImgList: [
    { required: true, validator: validateMainImgList, trigger: 'blur' },
  ],
}

//校验出发城市不为空
const validateStartCity = computed(() => {
  if (param.boxStartCity.length == 0) {
    param.boxCase = []
    return true
  }
  return false
})

</script>
<style scoped>
.tagCard {
  background-color: WhiteSmoke;
  border: 1px solid #DCDCDC;
  border-size: border-box;
  padding: 10px;
  border-radius: 5px;
  margin-right: 5px
}
</style>